/**
 * Created by Administrator on 2016/3/2.
 */

gpNamespace.GpPrepareGameLayer = cc.Layer.extend({
//	fromPoint: cc.p(100, cc.winSize.height / 2 ),
	tileSpace: 18,

	warnPoint: cc.p(168, cc.winSize.height / 2),
	isWarn:false,
	
    currentPlayers:0,
    headPosition:[cc.p(558, 235), cc.p(558, 633)],
    namePosition:[cc.p(695, 250), cc.p(695, 645)],
    kuangPosition:[cc.p(705, 245), cc.p(705, 645)],
    scoreLabelPosition:[cc.p(622, 220), cc.p(622, 618)],
    nickPosition:[cc.p(695, 260), cc.p(695, 655)],
    tuoguanPosition:[cc.p(538, 235), cc.p(538, 630)],
    
    ctor:function(){
        this._super();

        this.init();
    },

    init:function(){
        this.currentPlayers = 0;
        cc.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>preparegameLayer");
        // 顶部背景
        var background = new cc.Sprite(gpNamespace.pdkgame.Game_bg);
        background.attr({
            x: 0,
            y: 0,
            anchorX: 0,
            anchorY: 0
        });
        this.addChild(background);

        //锄大地标签     
        var middleTitle = new cc.Sprite(gpNamespace.pdkgame.Game_middletext);
        middleTitle.attr({
            x: cc.winSize.width / 2,
            y: cc.winSize.height / 2 + 50
        });
        middleTitle.setScale(0.8);
        this.addChild(middleTitle);

//        //锄大地标签底分
//        var middleTitleScore = new cc.Sprite(gpNamespace.game.Game_middleTitleScore);
//        middleTitleScore.attr({
//        	x: cc.winSize.width / 2 - 30,
//        	y: cc.winSize.height / 2 - 10
//        });
//        this.addChild(middleTitleScore);

        //底分
        var diFen = new tyNamespace.NumLayer(gpNamespace.difen, 12, 35);
        diFen.attr({
        	x: cc.winSize.width / 2  + 30,
        	y: cc.winSize.height / 2 +18
        });
        this.addChild(diFen);
        var size = cc.winSize;
        
        //新闻背景
        var newsBg = new cc.MenuItemImage(gpNamespace.mainSenceFirst.TopLayerMessageBackground,gpNamespace.mainSenceFirst.TopLayerMessageBackground,this.openSjpdCallback,this);
        newsBg.attr({
        	x: size.width/2,
        	y: size.height-50,
        	anchorX: 0.5,
        	anchorY: 0.5
        });
        var newsMenu = new cc.Menu(newsBg);
        newsMenu.attr({
        	x:0,
        	y:0,
        	anchorX:0,
        	anchorY:0
        });
        this.addChild(newsMenu);
        
        //新闻喇叭
        var newsHorn = new cc.Sprite(gpNamespace.mainSenceFirst.TopLayerMessageLaBa);
        newsHorn.attr({
        	x: size.width/2-350,
        	y: newsBg.getPositionY()
        });
        this.addChild(newsHorn);
        var scrollNews = new cc.LabelTTF("",gpNamespace.DEFAULTFONT,22);
//      scrollNews.setFontFillColor(cc.color.WHITE);
        scrollNews.setFontFillColor(cc.color(6, 255, 128, 255))	;
        scrollNews.attr({
        	x:70,
        	y: 3,
        	anchorX: 0,
        	anchorY: 0
        });
        this.scrollNews = scrollNews;
        newsBg.addChild(scrollNews);
        this.setNewsScroll();
        tyNamespace.addWaitLayer();

        //返回
        var backItem1 = new cc.Sprite(gpNamespace.pdkgame.Game_back);
        var backItem2 = new tyNamespace.maskSprite(gpNamespace.pdkgame.Game_back);
        var backItem = new cc.MenuItemSprite(backItem1, backItem2, this.backCallbackFunction, this);
        backItem.attr({
            x: 1197,
            y: 72
        });
        //换桌
        var changeItem1 = new cc.Sprite(gpNamespace.xinzeng.changeTableBnBig);
        var changeItem2 = new tyNamespace.maskSprite(gpNamespace.xinzeng.changeTableBnBig);
        var changeItem = new cc.MenuItemSprite(changeItem1, changeItem2, this.changeTableCallback, this);
        changeItem.attr({
            x: 200,
            y: 72
        });

        var backMenu = new cc.Menu(backItem, changeItem);
        backMenu.attr({
            x: 0,
            y: 0,
            anchorX:0,
            anchorY:0
        });
        this.addChild(backMenu);
        this.backMenu = backMenu;
        backMenu.setVisible(false);
    },

    headCallbackFunction: function (sender) {
    	cc.log("个人信息");

    	tyNamespace.setMenuEnable(sender);

    	gpNamespace.SoundManager.playEffect(gpNamespace.soundRes.ButtonEffect, false);

        if (gpNamespace.gameEnd || !currentNetManager.isStart)
            return;

        var player = sender.getUserData();
    	
    	var runningScene = cc.director.getRunningScene();
    	var modelLayerCancelable = new tyNamespace.ModelLayerCancelable();
    	var modelLayer = new tyNamespace.ModelLayer();
    	modelLayer.setTouchArea(cc.size(597, 413), cc.p(337, 170));
    	modelLayerCancelable.addChild(modelLayer);
    	runningScene.addChild(modelLayerCancelable, 100);

    	var gameUserInfoLayer = new gpNamespace.GameUserInfoLayer(player);
    	gameUserInfoLayer.attr({
    		x: 0,
    		y: cc.winSize.height
    	});
    	modelLayer.addChild(gameUserInfoLayer);
    	modelLayerCancelable.setName("innerUserInfo");

    	tyNamespace.AnimationManager.nodeJumpShow(gameUserInfoLayer, -cc.winSize.height);
    },

    //设置用户方法
    setUser: function (player) {
        //tyNamespace.removeWaitLayer();
        this.currentPlayers++;
        cc.log("someBody enter:" + this.currentPlayers);
        var self = this;
        if (this.currentPlayers > 2) {
            this.stopWaitingAVi();
            this.backMenu && this.backMenu.setVisible(false);
        } else {
            this.scheduleOnce(function(){
                if (!gpNamespace.IsInJs && this.currentPlayers < 3) {
                    cc.log("gpNamespace.IsInJs:"+gpNamespace.IsInJs);
                    self.backMenu && self.backMenu.setVisible(true);
                    self.runWaitingAvi();
                }
            },1);
        }
        if(gpNamespace.IsInJs){
            this.backMenu && this.backMenu.setVisible(false);
        }

        var userItem = player.userItem;

        cc.log("orderindex:" + player.orderIndex);

        if (player.orderIndex == 0) {
            var runningScene = cc.director.getRunningScene();
            var juhua = runningScene.getChildByName(gpNamespace.WAIT);

//            cc.log("juhua" + juhua);
            juhua && juhua.removeFromParent(true);
        }

        var headLayer = new cc.Layer();
        this.addChild(headLayer, 1, "headLayer" + userItem.wChairID);

        var goldLayer = new cc.Layer();
        headLayer.addChild(goldLayer, 1, "goldLayer");

        this.setUserHeadNode(player, headLayer);
        this.setUserNameLabel(userItem, goldLayer);
        this.setGoldNode(userItem, headLayer);
        //this.setOK(userItem,headLayer);
        this.setUserGold(userItem, goldLayer);
    },

    runWaitingAvi:function(){
        cc.log("##等待动画");
        var waitingAvi =  this.getChildByTag(123);
        if(waitingAvi){
            waitingAvi.setVisible(true);
            return;
        }
        var gameWaitingAvi = new ccs.Armature("mj_zbdh_0001u");
        gameWaitingAvi.getAnimation().playWithIndex(0);
        gameWaitingAvi.getAnimation().setSpeedScale(1);
        gameWaitingAvi.setScale(1);
        gameWaitingAvi.setAnchorPoint(0.5, 0.5);
        gameWaitingAvi.setPosition(640, 300);
        this.addChild(gameWaitingAvi,10,123);
        gameWaitingAvi.getAnimation().setMovementEventCallFunc(null, this);
    },

    stopWaitingAVi:function(){
        cc.log("##人全，去动画");
        var waitingAvi = this.getChildByTag(123);
        waitingAvi && waitingAvi.setVisible(false);
    },

    //设置打完后用户离开
    removeUser: function (orderIndex) {
    	var userHeadNode = this.getChildByTag(100 + orderIndex);
    	if (userHeadNode) {
    		userHeadNode.removeFromParent(true);
    		this.currentPlayers--;

    		if (this.currentPlayers < 3) {
    			this.backMenu && this.backMenu.setVisible(true);
    		}
    		cc.log("someBody leave:" + this.currentPlayers);
    	}

    	//this.removeChildByTag(140 + orderIndex);
    	//this.removeChildByTag(150 + orderIndex);
    	//this.removeChildByTag(110 + orderIndex);
    	//this.removeChildByTag(120 + orderIndex);
    	//this.removeChildByTag(130 + orderIndex);
    },
    
    addUserHead: function (texture, player) {
    	cc.log("addUserHead" + texture + ",player" + player);
    	
    	var headLayer = this.getChildByName("headLayer" + player.orderIndex);
    	
    	if (!headLayer)
    		return;
    	
    	var imgSprite;
    	
    	var headPosition = this.headPosition[player.orderIndex];

    	if (!texture) {
    		//var randomNum = Math.round(Math.random() * (800 - 1)) + 1;
    		//
    		//if (player.orderIndex == 0)
    		//	cc.sys.localStorage.setItem("myHeadId", randomNum);
    		
    		//var str = tyNamespace.FullZero(randomNum.toString(), 3);

    		imgSprite = new cc.Sprite(gpNamespace.xinzeng.QQ);
    	} else {
    		imgSprite = new cc.Sprite();
    		imgSprite.initWithTexture(texture);
    	}
    	
    	var size = imgSprite.getContentSize();

    	if (size.width != 80 || size.height != 80) {
    		var scaleX = 79 / size.width;
    		var scaleY = 79 / size.height;
    		imgSprite.setScale(scaleX, scaleY);
    	}

    	imgSprite.setPosition(headPosition.x + 2, headPosition.y + 3);
    	headLayer.addChild(imgSprite, 2);
    },

    //设置用户头像
    setUserHeadNode: function (player, headLayer) {
        var userItem = player.userItem;

        var userID = userItem.id;
        var headID = userItem.headId;

        //设置机器人性别  头像背景 和 声音 相关
        if (userID == 0) {
            if (headID <= 6)
                userItem.gender = 1;
            else
                userItem.gender = 0;
        }
        
        var headPosition = this.headPosition[userItem.wChairID];

        var userHeadBackgroundItem = new cc.MenuItemImage(gpNamespace.pdkgame.Game_headbg,gpNamespace.pdkgame.Game_headbg,this.headCallbackFunction,this);
        var userHeadBackgroundMenu = new cc.Menu(userHeadBackgroundItem);
        userHeadBackgroundMenu.setPosition(headPosition);
        userHeadBackgroundItem.setUserData(player);

        headLayer.addChild(userHeadBackgroundMenu, 3);
        
        var userHeadImgUrl = player.userItem.headImgUrl;

        cc.log("userHeadImgUrl:" + userHeadImgUrl);
        
        if (userHeadImgUrl == "") {
        	var userHeadNode = player.getUserHeadNode(player.userItem.headId, null, cc.size(79, 79));
            //
        	//userHeadNode.setTag(100 + player.orderIndex);
        	//userHeadNode.setPosition(headPosition.x - 38, headPosition.y - 35);
        	//headLayer.addChild(userHeadNode, 2);
            var img = new cc.Sprite(gpNamespace.xinzeng.QQ);
            var size = userHeadNode.getContentSize();
            userHeadNode.setScale(79 / size.width, 79 / size.height);
            userHeadNode.setPosition(headPosition.x, headPosition.y + 4);
            headLayer.addChild(userHeadNode, 2);

//        	if (!player.userItem.isVip)
        } else {
        	tyNamespace.loadImgByUrl(userHeadImgUrl, this.addUserHead, this, player);
    	}

        if(player.userItem.isVip){
            var vip = new cc.Sprite(gpNamespace.dj.VIP);
            vip.attr({
                x: 10,
                y: 55,
                anchorX: 0,
                anchorY: 0
            });
            vip.setScale(0.5);
            userHeadBackgroundItem.addChild(vip);
        }
    },

    //设置用户名字nick标签
    setUserNameLabel: function (userItem, headLayer) {
        cc.log("userItem.nickName:" +userItem.nickName);

        var userNameLabel = new cc.LabelTTF(userItem.nickName, "Consolas", 22);
        userNameLabel.setFontFillColor(cc.color(255, 255, 255, 255));

        userNameLabel.setTag(10 + userItem.wChairID);
        userNameLabel.setPosition(this.nickPosition[userItem.wChairID]);//设置位置
        headLayer.addChild(userNameLabel, 2, "nameLabel");
    },

    //设置透明框和金币的排列:0,1,2,3玩家
    setUserGold: function (userItem, headLayer) {
        var count = userItem.lScore;
        cc.log("count:" + count);

        if (!tyNamespace.isPositiveNumber(count))
            count = 0;

        var position = this.kuangPosition[userItem.wChairID];
        
        var middleGoldItem = new cc.Sprite(gpNamespace.pdkgame.Game_namebg);
        middleGoldItem.setPosition(position.x - 25, position.y - 14);
        headLayer.addChild(middleGoldItem);

        var countCell = new tyNamespace.NumLayer(count, 14, 65);
        countCell.setPosition(position.x, position.y - 24)
        
        if (userItem.wChairID == 1)
        	countCell.setPosition(position.x - 20, position.y - 24)
        
        headLayer.addChild(countCell, 2, "gold");
    },
    
    setGoldNode:function(userItem, headLayer){
    	var goldNode = new cc.Sprite(gpNamespace.pdkgame.Game_gold);
    	goldNode.setPosition(this.scoreLabelPosition[userItem.wChairID]);//设置位置
    	headLayer.addChild(goldNode, 2, "goldNode");
    },

    setNewsScroll:function(){
    	var i = 0;
    	var self = this;
    	this.schedule(function(){
    		if(typeof lastThreeNews != "undefined"){
    			if(lastThreeNews[i][2].length>32){
    				lastThreeNews[i][2] = lastThreeNews[i][2].substring(0,28)+"...";
    			}
//  			cc.log("lastThreeNews[i][2].length:"+lastThreeNews[i][2].length);
    			if(lastThreeNews[i][0] == 3){
    				self.scrollNews.setFontFillColor(cc.color(255,205,79,255));
    			}else{
    				self.scrollNews.setFontFillColor(cc.color(77,255,143, 255));
				}
    			self.scrollNews.setString(lastThreeNews[i][3]+":"+lastThreeNews[i][2]);
    			//self.fadeInThenOut(self.scrollNews);
    			i >= 2 ? i = 0 : i++;
    		}
    	},3.1);
    },
    
    fadeInThenOut: function(node){
    	node.runAction(new cc.FadeTo(0.2,255));
    	this.scheduleOnce(function(){
    		node.runAction(new cc.FadeOut(0.2));
    	},3);
    },
    
    openSjpdCallback:function(sender){
    	cc.log("世界频道显示");
//  	cc.director.runScene(new cc.TransitionFade(0.5, new gpNamespace.CddMainScene()));
    	gpNamespace.SoundManager.playEffect(gpNamespace.soundRes.ButtonEffect, false);
    	tyNamespace.setMenuEnable(sender);
    	var runningScene = cc.director.getRunningScene();
    	var modelLayerCancelable = new tyNamespace.ModelLayerCancelable();
    	var modelLayer = new tyNamespace.ModelLayer();
    	modelLayer.setTouchArea(cc.size(875, 568), cc.p(202, 70));
    	modelLayerCancelable.addChild(modelLayer);
    	runningScene.addChild(modelLayerCancelable, 4);

    	var sjpdLayer = new gpNamespace.SjpdLayer();
    	sjpdLayer.attr({
    		x: 0,
    		y: cc.winSize.height
    	});
    	modelLayer.addChild(sjpdLayer);
    	tyNamespace.AnimationManager.nodeJumpShow(sjpdLayer, -cc.winSize.height);
	},
    backCallbackFunction: function (sender) {
        cc.log("返回");

        tyNamespace.setMenuEnable(sender);

        gpNamespace.SoundManager.playEffect(gpNamespace.soundRes.ButtonBack, false);

        tyNamespace.duangDuangFirst(sender,function(){
            cc.audioEngine.stopMusic(true);
            gpNamespace.SoundManager.playMusic(gpNamespace.soundRes.BackgroundMusic, true);
//  		gpNamespace.SoundManager.playEffect(gpNamespace.soundRes.ButtonBack, false);

            var mjNet = gpNamespace.NetManager.getInstance();
            mjNet.removeMyListeners();

            gpNamespace.NetManager.instance = null;

            xinyou.netManager.leaveTable();
            gpNamespace.needLeaveRoom = true;
        });
    },
    changeTableCallback:function(sender){
        tyNamespace.setMenuEnable(sender);
        tyNamespace.addWaitLayer();

        var cddNet = gpNamespace.NetManager.getInstance();
        cddNet.removeMyListeners();
        gpNamespace.NetManager.instance = null;
        cc.log("##gpNamespace.playerLeaved:"+gpNamespace.playerLeaved);
        xinyou.netManager.leaveTable();
        gpNamespace.needLeaveRoom = false;
        this.removeAllChildren(true);
        this.init();

        var cddNet = gpNamespace.NetManager.getInstance();
        currentNetManager = cddNet;
        cddNet.addMyListeners();

        this.scheduleOnce(function () {
            xinyou.netManager.sitDown();
        }, 1);
    },
});